package org.noote.libs.tcpip;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import android.util.Log;

public class IPServer {

	private static final String TAG = "IPServer";

	private ServerSocket m_Socket = null;
	private ServerThread mServerThread = null;
	private IPEvent_Server _events = null;
	
	private boolean _bIsConnected = false;
	
	public IPServer()
	{

	}
	public IPServer(IPEvent_Server events)
	{
		this._events = events; 
	}
	
	public boolean isConnected(){return _bIsConnected;}

	public IPEvent_Server createServerEvents()
	{
		// by default return _events... need to be overloaded
		return _events;
	}

	public boolean create(int iPort) {

		try {
			Log.d(TAG, "Connecting...");
			m_Socket = new ServerSocket(iPort);
		} catch (UnknownHostException e) {
			Log.e(TAG, "UnknownHostException " + e.getMessage());
		} catch (IOException e) {
			Log.e(TAG, "IOException " + e.getMessage());
		} catch (Exception e) {
			Log.e(TAG, "Exception " + e.getMessage());
		}
		
		(mServerThread = new ServerThread(m_Socket)).start();

		return true;
	}
	
	public boolean close()
	{
		Log.d(TAG, "Close...");
		if(mServerThread != null)
		{
			mServerThread.interrupt();
			//mServerThread.destroy(); ?
		}
		return true;
	}
	
	private class ServerThread extends Thread {
		ServerSocket socket = null;
		
		public ServerThread(ServerSocket s) {
			socket = s;
		}
		
		@Override
		public void run() {
			try {
				while(true)
				{
					Socket receiver = socket.accept();
					(new IPServer_ConnectedThread(receiver, createServerEvents())).start();
				}
			} catch (IOException e) {
				e.printStackTrace();
				Log.e(TAG, "Thread catch...");
			}
		}
	}
}
